//
//  NetworkTools.swift
//  MySinaWeiBo
//
//  Created by zhangfuwei on 15/7/30.
//  Copyright © 2015年 zhangfuwei. All rights reserved.
//

import UIKit
import AFNetworking
private let FWErrorDomainName = "com.itheima.error.network"
///  网络错误信息 --枚举
private enum FWNetworkError : Int {
    
    case  emptyDataError = -1
    case  emptyTokenError = -2
    // 错误的详细描述
    private var errorDescription: String {
    
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "token为空"
        }
    }
    //  根据 int 值,返回对应的错误
    private func error() ->NSError {
        return NSError(domain: FWErrorDomainName, code:rawValue, userInfo: [FWErrorDomainName:errorDescription])
    }
}

private enum FWNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"

}

class NetworkTools: AFHTTPSessionManager {


    // 应用的相关信息
    let clientId = "261835978"
    let appSecret = "0d30098a2c7b6c1a91a12ef57e200b2f"
    //  回调地址
    let redirectUri = "http://www.baidu.com"
    
    //  MARK: 判断并生成 token 字典
    private func token(finished:FWfinishedCall) ->[String: AnyObject]? {
        if UserAccount.loadUserAcount()?.access_token == nil {
            let error = FWNetworkError.emptyTokenError.error()
            
            finished(result: nil, error: error)
            return nil
        }
        
        ///  成功后为什么没有回调呢?
//        finished(result: ["access_token": UserAccount.loadUserAcount()!.access_token!], error: nil)
        
        return ["access_token": UserAccount.loadUserAcount()!.access_token!]
    }
    
    
     //  MARK: 加载用户微博数据
    func loadStatus(since_id:Int? , max_id: Int?,finished:FWfinishedCall) {
        
//        since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//        max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。

        let urlString = "2/statuses/home_timeline.json"
        
//        let params = ["access_token": UserAccount.loadUserAcount()!.access_token!]

        ///  必须保证 params 有值
        guard var params = token(finished) else {
            ///  否则返回
            return
        }
        //  下拉参数大于0
        if since_id > 0 {
           params["since_id"] = since_id
        }
//        
//        //  上拉参数大于 0
//        if max_id > 0 {
//            params["max_id"] = max_id
//        }
        
        request(FWNetworkMethod.GET, urlString: urlString, parameters: params, finished: finished)
    }
    
    
    //  MARK:  加载用户信息
    func loadUserInf( uid:String , finished:FWfinishedCall) {
    
        let urlString = "2/users/show.json"
      
        let paragms :[String : AnyObject] = ["uid":uid, "access_token":(UserAccount.loadUserAcount()!.access_token)!]
        
      request(FWNetworkMethod.GET, urlString: urlString, parameters: paragms, finished: finished)
    }
    
    
    
    // MARK: 获取 token
    func loadToken(code: String , finishedCall: FWfinishedCall){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let pagram = ["client_id":clientId ,
            "client_secret":appSecret ,
            "redirect_uri" : redirectUri ,
            "code":code,
            "grant_type": "authorization_code"]

        request(FWNetworkMethod.POST, urlString: urlString, parameters: pagram, finished: finishedCall)

    }

    
    //  MARK:  对 AFN 网络请求方法以及 成功/失败回调方法的封装
    private func request(requestMethod: FWNetworkMethod ,urlString: String!,parameters: AnyObject!, finished:FWfinishedCall) {
        
        ///  成功回调
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = {(_ , JSON) -> Void in
            
            if let result = JSON as? [String : AnyObject] {
//                print("打印返回的非空数据")
//                print(result)
                finished(result: result, error: nil)
            } else {
                print("没有数据的回调")
                
                finished(result: nil, error:  FWNetworkError.emptyDataError.error())
            }
            
            
        }
        ///  失败回调
        let failedCallback: (NSURLSessionDataTask!, NSError!) -> Void  = {(_ , error ) -> Void in
            
            print(error)
            finished(result: nil, error: error)
        }
        
        ///  根据枚举的情况调用不同请求
        switch requestMethod {
        case .GET:GET(urlString, parameters: parameters, success: successCallBack, failure: failedCallback)
        case .POST:POST(urlString, parameters: parameters, success: successCallBack, failure: failedCallback)
        }
    }
    
    //  MARK: 对外开放一个网络请求单例接口
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        
        let tools = NetworkTools(baseURL: baseURL)
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>

        return tools
        
        }()
    
    // MARK: 返回授权网址
    func OauthUrl() ->(NSURL) {
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
        return url
    }
    
    
    ///  网络回调起个别名
    typealias FWfinishedCall = (result: [String : AnyObject]?,error : NSError? ) ->()
    

}
